package com.example.common.security;

import com.example.domain.entity.Menu;
import com.example.domain.entity.User;
import lombok.Getter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

public class UserDetailsImpl implements UserDetails {

    @Getter
    private final User user;
    
    @Getter
    private final List<String> roles;
    
    @Getter
    private final List<String> permissions;
    
    @Getter
    private final List<Menu> menus;

    private final Collection<? extends GrantedAuthority> authorities;

    public UserDetailsImpl(User user, List<String> roles, List<String> permissions, List<Menu> menus) {
        this.user = user;
        this.roles = roles;
        this.permissions = permissions;
        this.menus = menus;
        
        // 将权限字符串转换为 GrantedAuthority 对象
        this.authorities = permissions.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return "1".equals(user.getStatus());
    }
} 